package com.zys.http.extension.intention;

import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.codeInspection.util.IntentionFamilyName;
import com.intellij.codeInspection.util.IntentionName;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.zys.http.extension.service.Bundle;
import com.zys.http.extension.service.NotifyService;
import com.zys.http.processor.ProcessorContext;
import com.zys.http.tool.SystemTool;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

/**
 * @author zys
 * @since 2025-01-21
 */
public class CopyApiIntentionAction<T extends PsiElement> extends PsiElementBaseIntentionAction {
    private Class<T> clazz;

    protected void setClazz(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {
        T method = PsiTreeUtil.getParentOfType(element, clazz);

        if (Objects.isNull(method)) {
            return;
        }

        String apiPath = ProcessorContext.apiPath(method, project);
        if (Objects.isNull(apiPath)) {
            return;
        }
        SystemTool.copy2Clipboard(apiPath);

        NotifyService.instance(project).info(Bundle.get("http.api.tree.method.right.menu.action.copy.api.msg"));
    }

    @Override
    public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement psiElement) {
        T method = PsiTreeUtil.getParentOfType(psiElement, clazz);
        return Objects.nonNull(method) && (ProcessorContext.isSpringMethod(method) || ProcessorContext.isJaxRsMethod(method));
    }

    @Override
    public @NotNull @IntentionName String getText() {
        return Bundle.get("http.api.tree.method.right.menu.action.copy.api");
    }

    @Override
    public @NotNull @IntentionFamilyName String getFamilyName() {
        return getText();
    }

    @Override
    public boolean startInWriteAction() {
        return false;
    }
}
